<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #deptName="{ model, field }">
        <ddDepartment v-model:value="model[field]" :placeholder="'请选择' + model.label"
          @success="e => { handleSuccess1(e, model, field) }">
        </ddDepartment>
      </template>
      <template #pid="{ model, field }">
        <ApiTreeSelect ref="treeSelectRef" resultField='data' labelField='categoryName' valueField='categoryId'
          childrenField='children' v-model:value="model[field]" :placeholder="'请选择'" :api=categoryList>
        </ApiTreeSelect>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm, ApiTreeSelect } from '@/components/Form';
import { formSchema } from './menu.data';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { BasicTree, TreeItem } from '@/components/Tree';
import { categoryList } from '@/api/heng/ex';

import { getAllDeptListApi } from '@/api/sys/sysData';
import { useMessage } from '@/hooks/web/useMessage';
import ddDepartment from '@/views/bookManage/components/ddDepartment/index.vue';

const treeSelectRef = ref();
const { createMessage } = useMessage();

import { categorySave } from '@/api/heng/ex';

defineOptions({ name: 'MenuDrawer' });

const emit = defineEmits(['success', 'register']);
const treeData = ref<TreeItem[]>([]);

const isUpdate = ref(true);
const id = ref("")

// const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
//   labelWidth: 100,
//   schemas: formSchema,
//   showActionButtonGroup: false,
//   baseColProps: { lg: 12, md: 24 },
// });
const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {

  resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  fetch();
  if (unref(isUpdate)) {
    id.value = data.record.categoryId;

    setFieldsValue({
      ...data.record,
    });
  };
  treeSelectRef.value.fetch();


});


async function fetch() {
  await getAllDeptListApi(null).then((res) => {
    if (res.code == 200) {
      treeData.value = res.data;
    } else {
      createMessage.error(res.message);
    }
  });
}


const getTitle = computed(() => (!unref(isUpdate) ? '新增分类' : '编辑分类'));

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    // TODO custom api
    console.log(values);
    values.categoryId = unref(id);
    categorySave(values).then(res => {
      closeDrawer();
      emit('success');
    });
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

function handleSuccess1(e, model, field) {
  // console.log("_---e:",e)
  model[field] = e.title;
  model.deptId = e.deptId;
  model.categoryName = e.title;
}
</script>
